<template>
	<div class="content-manage">
		<el-tabs v-model="activeTab">
			<!-- 轮播图管理 -->
			<el-tab-pane label="轮播图管理" name="carousel">
				<el-row style="margin-bottom: 8px;">
					<el-col>
						<el-button type="danger" icon="delete" @click="batchDeleteCarousels"
								   :disabled="selectedCarousels.length === 0">批量删除
						</el-button>
						<el-button type="success" icon="plus" @click="openCarouselDialog">新增轮播图</el-button>
						<el-input v-model="carouselQuery.keyword" @keyup.enter="handleSearch('carousel')" clearable
								  placeholder="搜索标题" style="width: 200px; margin-left: 10px">
							<template #append>
								<el-button icon="search" @click="handleSearch('carousel')"/>
							</template>
						</el-input>
						<el-select v-model="carouselQuery.is_active" @change="handleSearch('carousel')"
								   placeholder="状态筛选" style="width: 120px; margin-left: 10px">
							<el-option label="全部" :value="null"/>
							<el-option label="启用" :value="true"/>
							<el-option label="禁用" :value="false"/>
						</el-select>
					</el-col>
				</el-row>

				<el-table :data="carouselList" border @selection-change="handleCarouselSelection">
					<el-table-column type="selection" width="55"/>
					<el-table-column label="标题" prop="title"/>
					<el-table-column label="图片" width="180">
						<template #default="{row}">
							<el-image :src="row.image" style="width: 100px; height: 60px" fit="cover"/>
						</template>
					</el-table-column>
					<el-table-column label="排序" prop="order" sortable/>
					<el-table-column label="状态" width="100">
						<template #default="{row}">
							<el-tag :type="row.is_active ? 'success' : 'danger'">
								{{ row.is_active ? '启用' : '禁用' }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="操作" width="200" align="center">
						<template #default="{row}">
							<el-button size="small" @click="toggleCarouselStatus(row)">{{
									row.is_active ? '禁用' : '启用'
								}}
							</el-button>
							<el-button size="small" @click="editCarousel(row)">编辑</el-button>
						</template>
					</el-table-column>
				</el-table>

				<div class="pagination">
					<el-pagination
						background
						layout="prev, pager, next"
						:total="carouselTotal"
						v-model:current-page="carouselQuery.page"
						@current-change="loadCarousels"
					/>
				</div>
			</el-tab-pane>

			<!-- 公告管理 -->
			<el-tab-pane label="公告管理" name="announcement">
				<el-row style="margin-bottom: 8px;">
					<el-col>
						<el-button type="danger" icon="delete" @click="batchDeleteAnnouncements"
								   :disabled="selectedAnnouncements.length === 0">批量删除
						</el-button>
						<el-button type="success" icon="plus" @click="openAnnouncementDialog">新增公告</el-button>
						<el-input v-model="announcementQuery.keyword" clearable
								  @keyup.enter="handleSearch('announcement')" placeholder="搜索标题/内容"
								  style="width: 200px; margin-left: 10px">
							<template #append>
								<el-button icon="search" @click="handleSearch('announcement')"/>
							</template>
						</el-input>
						<el-select v-model="announcementQuery.is_active" @change="handleSearch('announcement')"
								   placeholder="状态筛选" style="width: 120px; margin-left: 10px">
							<el-option label="全部" :value="null"/>
							<el-option label="启用" :value="true"/>
							<el-option label="禁用" :value="false"/>
						</el-select>
					</el-col>
				</el-row>

				<el-table :data="announcementList" border @selection-change="handleAnnouncementSelection">
					<el-table-column type="selection" width="55"/>
					<el-table-column label="标题" prop="title"/>
					<el-table-column label="内容" prop="content" show-overflow-tooltip/>
					<el-table-column label="状态" width="100">
						<template #default="{row}">
							<el-tag :type="row.is_active ? 'success' : 'danger'">
								{{ row.is_active ? '启用' : '禁用' }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="操作" width="240" align="center">
						<template #default="{row}">
							<el-button size="small" @click="toggleAnnouncementPin(row)">
								{{ row.is_pinned ? '取消置顶' : '置顶' }}
							</el-button>
							<el-button size="small" @click="toggleAnnouncementStatus(row)">
								{{ row.is_active ? '禁用' : '启用' }}
							</el-button>
							<el-button size="small" @click="editAnnouncement(row)">编辑</el-button>
						</template>
					</el-table-column>
				</el-table>

				<div class="pagination">
					<el-pagination
						background
						layout="prev, pager, next"
						:total="announcementTotal"
						v-model:current-page="announcementQuery.page"
						@current-change="loadAnnouncements"
					/>
				</div>
			</el-tab-pane>
		</el-tabs>

		<!-- 轮播图编辑对话框 -->
		<el-dialog :title="carouselForm.id ? '编辑轮播图' : '新增轮播图'" v-model="carouselDialogVisible">
			<el-form :model="carouselForm" :rules="carouselRules" label-width="100px">
				<el-form-item label="标题" prop="title">
					<el-input v-model="carouselForm.title"/>
				</el-form-item>
				<el-form-item label="图片" prop="image">
					<el-upload
						:show-file-list="false"
						:auto-upload="false"
						:on-change="handleImageUpload"
						accept="image/*"
					>
						<el-button type="primary" :loading="uploadLoading">点击上传</el-button>
						<template #tip>
							<div class="el-upload__tip">
								建议尺寸：1200x400px，支持格式：JPG/PNG/JPEG
							</div>
						</template>
					</el-upload>
					<el-image v-if="carouselForm.image" :src="carouselForm.image" class="preview-image"/>
				</el-form-item>
				<el-form-item label="链接" prop="url">
					<el-input v-model="carouselForm.url"/>
				</el-form-item>
				<el-form-item label="排序" prop="order">
					<el-input-number v-model="carouselForm.order" :min="0"/>
				</el-form-item>
				<el-form-item label="启用状态">
					<el-switch v-model="carouselForm.is_active"/>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="carouselDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="saveCarousel">保存</el-button>
			</template>
		</el-dialog>

		<!-- 公告编辑对话框 -->
		<el-dialog :title="announcementForm.id ? '编辑公告' : '新增公告'" v-model="announcementDialogVisible">
			<el-form :model="announcementForm" :rules="announcementRules" label-width="100px">
				<el-form-item label="标题" prop="title">
					<el-input v-model="announcementForm.title"/>
				</el-form-item>
				<el-form-item label="内容" prop="content">
					<el-input v-model="announcementForm.content" type="textarea" rows="6"/>
				</el-form-item>
				<el-form-item label="置顶状态">
					<el-switch v-model="announcementForm.is_pinned"/>
				</el-form-item>
				<el-form-item label="启用状态">
					<el-switch v-model="announcementForm.is_active"/>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="announcementDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="saveAnnouncement">保存</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import {ref, reactive, onMounted, watch} from 'vue'
import {debounce} from 'lodash-es'
import {ElMessage, ElMessageBox} from 'element-plus'
import {
	carousel_list,
	carousel_create,
	carousel_update,
	carousel_delete,
	announcement_list,
	announcement_create,
	announcement_update,
	announcement_delete,
	toggle_announcement_pin,
	toggle_carousel_status,
	toggle_announcement_status
} from '/@/api/home'

const uploadLoading = ref(false)
const currentFile = ref(null)


// 公共状态
const activeTab = ref('carousel')

// 轮播图相关状态
const carouselList = ref([])
const carouselTotal = ref(0)
const carouselQuery = reactive({
	page: 1,
	page_size: 10,
	is_active: null,
	keyword: ''
})
// 公告相关状态
const announcementQuery = reactive({
	page: 1,
	page_size: 10,
	keyword: '',
	is_active: null
})
const announcementList = ref([])
const announcementTotal = ref(0)

// 补充缺失的状态声明
const selectedCarousels = ref([])
const selectedAnnouncements = ref([])
const carouselDialogVisible = ref(false)
const announcementDialogVisible = ref(false)

// 表单数据
const carouselForm = reactive({
	id: null,
	title: '',
	image: null,
	url: '',
	order: 0,
	is_active: true
})

const announcementForm = reactive({
	id: null,
	title: '',
	content: '',
	is_pinned: false,
	is_active: true
})

// 表单验证规则
const carouselRules = reactive({
	title: [{required: true, message: '请输入标题', trigger: 'blur'}],
	image: [{required: true, message: '请上传图片', trigger: 'change'}]
})

const announcementRules = reactive({
	title: [{required: true, message: '请输入标题', trigger: 'blur'}],
	content: [{required: true, message: '请输入内容', trigger: 'blur'}]
})

// 初始化加载
onMounted(() => {
	loadCarousels()
	loadAnnouncements()
})

// 新增搜索处理逻辑
const handleSearch = (type) => {
	if (type === 'carousel') {
		carouselQuery.page = 1
		loadCarousels()
	} else {
		announcementQuery.page = 1
		loadAnnouncements()
	}
}

// 添加防抖监听搜索词
watch(
	() => carouselQuery.keyword,
	debounce(() => {
		handleSearch('carousel')
	}, 500)
)

watch(
	() => announcementQuery.keyword,
	debounce(() => {
		handleSearch('announcement')
	}, 500)
)

// 加载轮播图数据
const loadCarousels = async () => {
	const params = {
		...carouselQuery,
	}
	const res = await carousel_list(params)
	carouselList.value = res.data.carousels
	carouselTotal.value = res.data.total
}

// 加载公告数据
const loadAnnouncements = async () => {
	const params = {
		...announcementQuery,
	}
	const res = await announcement_list(params)
	announcementList.value = res.data.announcements
	announcementTotal.value = res.data.total
}

// 表格选择处理
const handleCarouselSelection = (selection) => {
	selectedCarousels.value = selection.map(item => item.id)
}

const handleAnnouncementSelection = (selection) => {
	selectedAnnouncements.value = selection.map(item => item.id)
}

// 弹窗操作
const openCarouselDialog = (row) => {
	if (row.id) {
		Object.assign(carouselForm, row)
	} else {
		Object.assign(carouselForm, {
			id: null,
			title: '',
			image: '',
			url: '',
			order: 0,
			is_active: true
		})
	}
	carouselDialogVisible.value = true
}

const openAnnouncementDialog = (row) => {
	if (row.id) {
		Object.assign(announcementForm, row)
	} else {
		Object.assign(announcementForm, {
			id: null,
			title: '',
			content: '',
			is_pinned: false,
			is_active: true
		})
	}
	announcementDialogVisible.value = true
}

// 保存操作
const saveCarousel = async () => {
	const formData = new FormData()
	const uploadFile = currentFile.value || await fetch(carouselForm.image.replace('http://192.168.124.11:8000', '/api'))
		.then(res => res.blob())
		.then(blob => new File([blob], carouselForm.image.split('/').pop(), {type: blob.type}))
	Object.entries(carouselForm).forEach(([key, value]) => {
		if (key === 'image') {
			if (uploadFile) {
				formData.append(key, uploadFile)
			}
		} else {
			formData.append(key, value)
		}
	})
	try {
		if (carouselForm.id) {
			await carousel_update(carouselForm.id, formData)
		} else {
			await carousel_create(formData)
		}
		loadCarousels()
		carouselDialogVisible.value = false
		currentFile.value = null;
		ElMessage.success('操作成功')

	} catch (error) {
		ElMessage.error('操作失败')
	}
}

const saveAnnouncement = async () => {
	try {
		if (announcementForm.id) {
			await announcement_update(announcementForm.id, announcementForm)
		} else {
			await announcement_create(announcementForm)
		}
		loadAnnouncements()
		announcementDialogVisible.value = false
		ElMessage.success('操作成功')
	} catch (error) {
		ElMessage.error('操作失败')
	}
}

// 图片上传处理
const handleImageUpload = (file, fileList) => {
	console.log(file)
	try {
		uploadLoading.value = true
		// 确保获取的是File对象
		currentFile.value = file.raw

		carouselForm.image = URL.createObjectURL(currentFile.value)

		// 立即上传文件到服务器
		// const formData = new FormData()
		// formData.append('file', rawFile)
		// const res = await uploadImageAPI(formData)

		// // 使用服务器返回的URL替换临时URL
		// if (res.code === 200) {
		//   carouselForm.image = res.data.url
		//   ElMessage.success('图片上传成功')
		// }
	} catch (error) {
		ElMessage.error('图片上传失败：' + error.message)
	} finally {
		uploadLoading.value = false
	}
}

// 批量删除
const batchDeleteCarousels = async () => {
	try {
		await ElMessageBox.confirm('确定删除选中的轮播图吗？', '警告')
		for (const id of selectedCarousels.value) {
			await carousel_delete(id)
		}
		loadCarousels()
		ElMessage.success('删除成功')
	} catch (error) {
		// 用户取消删除
	}
}

const batchDeleteAnnouncements = async () => {
	try {
		await ElMessageBox.confirm('确定删除选中的公告吗？', '警告')
		for (const id of selectedAnnouncements.value) {
			await announcement_delete(id)

		}
		loadAnnouncements()
		ElMessage.success('删除成功')
	} catch (error) {
		// 用户取消删除
	}
}

// 编辑操作
const editCarousel = (row) => {
	openCarouselDialog(row)
}

const editAnnouncement = (row) => {
	openAnnouncementDialog(row)
}

// 补充公告状态切换
const toggleAnnouncementStatus = async (item) => {
	await toggle_announcement_status(item.id)
	item.is_active = !item.is_active
	ElMessage.success(`已${item.is_active ? '启用' : '禁用'}`)
}

const toggleCarouselStatus = async (item) => {
	await toggle_carousel_status(item.id)
	item.is_active = !item.is_active
	ElMessage.success(`已${item.is_active ? '启用' : '禁用'}`)
}

const toggleAnnouncementPin = async (item) => {
	await toggle_announcement_pin(item.id)
	item.is_pinned = !item.is_pinned
	ElMessage.success(`已${item.is_pinned ? '置顶' : '取消置顶'}`)
}
</script>

<style scoped>
.content-manage {
	padding: 20px;
	background: #fff;
	border-radius: 4px;
}

.preview-image {
	margin-top: 10px;
	max-width: 300px;
	max-height: 200px;
}

.pagination {
	margin-top: 20px;
	display: flex;
	justify-content: flex-end;
}
</style>
